package helper;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import cn.hutool.crypto.symmetric.SymmetricCrypto;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.util.Random;

public class FourJiaMi {

	static {
		Security.addProvider(new BouncyCastleProvider());
	}

	// key必须是16字节，即128位
	final static String key = "sm4demo123456789";

	// 指明加密算法和秘钥

	// 加密为16进制，也可以加密成base64/字节数组
	public static String encryptSm4(String keys, String plaintext) {
		SymmetricCrypto sm4 = new SymmetricCrypto("SM4/ECB/PKCS5Padding", keys.getBytes());
		return sm4.encryptHex(plaintext);
	}

	// 解密
	public static String decryptSm4(String keys, String ciphertext) {
	 
		SymmetricCrypto sm4 = new SymmetricCrypto("SM4/ECB/PKCS5Padding", keys.getBytes());
		return sm4.decryptStr(ciphertext);
	}

	public static String getRandomString(int length) {

		String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

		Random random = new Random();

		StringBuffer sb = new StringBuffer();

		for (int i = 0; i < length; i++) {

			int number = random.nextInt(62);

			sb.append(str.charAt(number));

		}

		return sb.toString();

	}

	public static void main(String[] args) {
		String content = "hello sm4";
		String plain = encryptSm4(key,content);
		String cipher = decryptSm4(key,plain);
		System.out.println(plain + "\n" + cipher);
	}
}
